package com.smasher.pdf.afreakyelf

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.rajat.pdfviewer.PdfRendererView
import com.rajat.pdfviewer.util.FileUtils.fileFromAsset
import com.smasher.pdf.R
import com.smasher.pdf.databinding.ActivityAfreakyelfPdfBinding
import com.smasher.widget.base.BaseActivity
import java.io.File

class AfreakyelfPdfActivity : BaseActivity() {

    private lateinit var mBinding: ActivityAfreakyelfPdfBinding
    private lateinit var pdfView: PdfRendererView
    private var name: String = ""
    private var type = 0

    /**
     * 初始化参数，从Bundle中获取类型和名称
     */
    override fun initParams(bundle: Bundle?) {
        super.initParams(bundle)
        if (bundle != null) {
            type = bundle.getInt(KEY_TYPE)
            name = bundle.getString(KEY_VALUE) ?: ""
        }
    }

    override fun getRootView(): View {
        mBinding = ActivityAfreakyelfPdfBinding.inflate(layoutInflater)
        return mBinding.root
    }

    /**
     * 初始化视图，设置PDF渲染器和工具栏
     */
    override fun initView() {

        pdfView = mBinding.pdfView
        pdfView.statusListener = object : PdfRendererView.StatusCallBack {
            override fun onPdfLoadStart() {
                Log.i(TAG, "onPdfLoadStart")
            }

            override fun onPdfLoadProgress(
                progress: Int,
                downloadedBytes: Long,
                totalBytes: Long?
            ) {
                //Download is in progress
            }

            override fun onPdfLoadSuccess(absolutePath: String) {
                Log.i(TAG, "onPdfLoadSuccess")
            }

            override fun onError(error: Throwable) {
                Log.i(TAG, "onError")
            }

            override fun onPageChanged(currentPage: Int, totalPage: Int) {
                //Page change. Not require
            }
        }

        mBinding.toolbar.setNavigationOnClickListener { finish() }
        mBinding.toolbar.title = name
        mBinding.toolbar.setOnMenuItemClickListener { item: MenuItem ->
            when (item.itemId) {

                R.id.menu_item_select -> {
                    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
                    intent.addCategory(Intent.CATEGORY_OPENABLE)
                    intent.setType("application/pdf")
                    fileSelectorLauncher.launch(intent)
                    return@setOnMenuItemClickListener true
                }

                else -> {
                    return@setOnMenuItemClickListener false
                }
            }
        }
    }

    /**
     * 根据文件名显示PDF文件
     */
    private fun showFile(name: String) {
        val parent = getExternalFilesDir("PDF")

        // 确保父目录存在，如果不存在则创建
        if (parent != null && !parent.exists()) {
            parent.mkdirs() // 使用 mkdirs() 替代 mkdir() 以确保所有必要的父目录都被创建
        }

        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "name is empty", Toast.LENGTH_SHORT).show()
            return
        }

        val file = File(parent, name)
        if (file.exists()) {
            showPdfFromFile(file)
        } else {
            Toast.makeText(this, "file is not exist", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 初始化数据，根据类型显示不同的PDF内容
     */
    override fun initData() {
        when (type) {
            1 -> showPdfFromAsset(name)
            2 -> showFile(name)
            3 -> showPdfFromUri(Uri.parse(name))
            4 -> showPdfFromUrl(name)
        }
    }

    /**
     * 从assets中加载PDF文件
     */
    private fun showPdfFromAsset(assetName: String) {
        initPdfViewerWithPath(assetName)
    }


    /**
     * 从文件中加载PDF文件
     */
    private fun showPdfFromFile(file: File) {
        pdfView.initWithFile(file = file)
        pdfView.jumpToPage(1)
    }

    /**
     * 从Uri中加载PDF文件
     */
    private fun showPdfFromUri(uri: Uri) {
        pdfView.initWithUri(uri = uri)
        pdfView.jumpToPage(1)
    }

    /**
     * 从URL中加载PDF文件
     */
    private fun showPdfFromUrl(url: String) {
        pdfView.initWithUrl(
            url = url,
            lifecycleCoroutineScope = lifecycleScope,
            lifecycle = lifecycle
        )
        pdfView.jumpToPage(1)
    }


    /**
     * 初始化PDF渲染器，根据文件路径加载PDF
     */
    private fun initPdfViewerWithPath(filePath: String) {
        if (TextUtils.isEmpty(filePath)) {
            Log.e(TAG, "请检查文件路径 ")
            return
        }
        try {
            val file = fileFromAsset(this, filePath)
            pdfView.initWithFile(file)
            pdfView.jumpToPage(1)
        } catch (e: Exception) {
            Log.e(TAG, "initPdfViewerWithPath: ")
        }
    }


    private val fileSelectorLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { it ->
            if (it.resultCode == RESULT_OK) {
                val data = it.data
                if (data != null && data.data != null) {
                    val selectedPdfUri = data.data
                    selectedPdfUri?.let {
                        showPdfFromUri(it)
                    }
                }
            }
        }

    companion object {
        const val TAG: String = "PDF"

        private const val KEY_TYPE = "TYPE"
        private const val KEY_VALUE = "VALUE"
    }
}
